#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


//stdlib --> malloc big memory
void test_malloc_big_memory(){
    const char * see_mem_cmd = "ps -eo cmd,pid,rss,vsize | grep main | grep -v grep";
    char* * p = calloc(1024*1024, sizeof(char*)); //1M ptr
    printf("calloc ptr buffer  ...\n");
    system(see_mem_cmd);


    long long i =0;
    for( ; i < 1024 * 1024  ; ++i){
        p[i] = calloc(1, 1024*10);
    }
    printf("calloc 1024*1024*1024*10 mem ...\n");
    system(see_mem_cmd);

    printf("begin free  ...\n");
    /*   unorder free 
    for(i = 1024*1024-1; i >= 1; --i){
        free(p[i]);
    }*/
    for( i = 0; i < 1024*1024-1; ++i){
        free(p[i]);
    }
    printf("free end but, left 1 block(10K) ...\n");
    system(see_mem_cmd);

    char * m = p[i];
    free(p);

    printf("sleep 20sec  ...\n");
    sleep(20);
    
    free(m);
    printf("free the last block(10K) ...\n");
    system(see_mem_cmd);


    //int*  ptr = (int *)(0x4c9e993000);
    //printf("invalid read %d\n", *ptr);
    
    //sleep(100);
}


void test(){
    char * tmp = (char*)calloc(1, 128 * 1024 *1024);
    char * ptr = (char*)calloc(1,1);
    
    int * iptr = (int*)(ptr+32*1024*1024);
    printf("ptr %d\n", *iptr);
}

int main(){
    //test();
    test_malloc_big_memory();
    return 0;
}
